package com.wang.jmonkey.gateway.handler.auth.authorization;

import com.alibaba.fastjson.JSONObject;
import com.wang.jmonkey.common.result.HttpResult;
import org.apache.http.HttpStatus;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @Description  403拒绝访问异常处理
 * @Author HeJiawang
 * @Date 2021/5/31 13:23
 */
public class AccessDeniedHandler implements ServerAccessDeniedHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        HttpResult<Void> result = new HttpResult<Void>()
                .setSuccess(false)
                .setCode(HttpStatus.SC_FORBIDDEN)
                .setMsg(denied.getMessage());

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(JSONObject.toJSONString(result).getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer))
                .doOnError((error) -> DataBufferUtils.release(buffer));
    }
}
